<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>闭包-节流(Throttling)</title>
    <style>
        .father {
            display: flex;
            justify-content: center;
            align-items: center;
        }
    </style>
</head>
<body>
    <div class="father">
        <div class="son"></div>
        <h3>什么是节流？</h3>
        <h5>它可以将一个函数的调用频率限制在一定阈值内，例如 1s，那么 1s 内这个函数一定不会被调用两次</h5>
    </div>
    <script>
        function throttlingFunc(fn, waitTime) {
            let timer
            return function() {
                let contxt = this
                let args = arguments

                //判断：如果有timer，说明上一个时间还未结束
                if(timer) {
                    return  //没结束你就return停止，等上一个结束
                }
                timer = setTimeout(() => {
                    coloring.apply(contxt,args)
                    timer = null  //timer不在事件完成之后给null的话，上面的if会一直判断为真
                }, waitTime);
            }
        }
        function coloring() {
            let r = Math.floor(Math.random() * 255)
            let g = Math.floor(Math.random() * 255)
            let b = Math.floor(Math.random() * 255)
            document.body.style.background = `rgb(${r},${g},${b})`
            console.log(r, g, b)
        }
        window.addEventListener('resize',throttlingFunc(coloring,2000))

    </script>
</body>
</html>